package top.shiyiri.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import top.shiyiri.community.bean.Comment;
import top.shiyiri.community.bean.DiscussPost;
import top.shiyiri.community.bean.Event;
import top.shiyiri.community.event.EventProducer;
import top.shiyiri.community.service.CommentService;
import top.shiyiri.community.service.DiscussPostService;
import top.shiyiri.community.util.CommunityConstant;
import top.shiyiri.community.util.HostHolder;

import java.util.Date;
import java.util.HashMap;

/**
 * @author Aunean
 * @date 2022/3/15 21:22
 */
@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {

    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private DiscussPostService discussPostService;

    @PostMapping("/add/{discussPostId}")
    public String add(@PathVariable("discussPostId") int discussPostId,
                      Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());

        commentService.addComment(comment);
        //触发评论事件
        Event event = new Event();
        event.setTopic(TOPIC_COMMENT);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(comment.getEntityType());
        event.setEntityId(comment.getEntityId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("postId", discussPostId);
        event.setData(map);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if(comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findServiceById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        return "redirect:/discuss/detail/" + discussPostId;
    }

}
